package com.wdy.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wdy.entities.SecurityUser;
import com.wdy.entities.User;
import com.wdy.servicebase.utils.R;
import com.wdy.servicebase.utils.ResponseUtil;
import com.wdy.ssafe.TokenManager;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Slf4j
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

  private TokenManager tokenManager;
  private AuthenticationManager authenticationManager;
  private RedisTemplate<String, Object> redisTemplate;

  public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager,
      RedisTemplate<String, Object> redisTemplate) {
    this.redisTemplate = redisTemplate;
    this.tokenManager = tokenManager;
    this.authenticationManager = authenticationManager;
    super.setPostOnly(false);
    super.setRequiresAuthenticationRequestMatcher(new
        AntPathRequestMatcher("/admin/acl/login", HttpMethod.POST.name()));
  }

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request,
      HttpServletResponse response) throws AuthenticationException {
    try {
      User user = new ObjectMapper().readValue(request.getInputStream(), User.class);

      UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
          user.getUsername(), user.getPassword());

      return this.authenticationManager.authenticate(authRequest);
    } catch (IOException e) {
      log.info("登录失败，账号密码解析失败");
      throw new UsernameNotFoundException("登录失败，账号密码解析失败");
    }
  }

  @Override
  protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
      FilterChain chain, Authentication authResult) throws IOException, ServletException {
    SecurityUser userDetails = (SecurityUser) authResult.getPrincipal();
    String token = tokenManager.createToken(userDetails.getUsername());
    redisTemplate.opsForValue()
        .set(userDetails.getUsername(), userDetails.getPermissionValueList());
    ResponseUtil.out(response, R.ok().data("token", token));
  }

  @Override
  protected void unsuccessfulAuthentication(HttpServletRequest request,
      HttpServletResponse response, AuthenticationException failed)
      throws IOException, ServletException {
    ResponseUtil.out(response, R.error());
  }
}
